import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
import type { API } from '@/api/typings.d.ts';
import controllers from '@/api';
import { UserRoleEnum } from '@/enums/UserRoleEnum';

export const userLoginUserStore = defineStore('userLogin', () => {
		const loginUser = ref<API.LoginUserVO>({
			userName: 'no login',
			userRole: UserRoleEnum.ANONYMOUS
		});

		function setLoginUser(user: API.LoginUserVO) {
			loginUser.value = user;
		}

		async function asyncLogin() {
			const loginUserUsingGet = controllers.userController.getLoginUser();
			return loginUserUsingGet.then((response) => {
				loginUser.value = response.data?.data || { userRole: UserRoleEnum.ANONYMOUS };
				return Promise.resolve(true);
			}).catch(() => {
				loginUser.value = { userRole: UserRoleEnum.ANONYMOUS };
				return Promise.reject(false);
			});

		}

		async function login() {
			await asyncLogin();
		}

		function isLogin() {
			return loginUser.value.userRole !== UserRoleEnum.ANONYMOUS;
		}

		function getRole():UserRoleEnum{
			return loginUser.value.userRole;
		}
		return { loginUser, asyncLogin, login, isLogin, setLoginUser,getRole };
	}
);

